package com.bitoon.basketdudes.jpa;

import java.util.*;
import javax.persistence.*;
import org.apache.log4j.*;

public class PersistenceManager {

    public static final boolean DEBUG = true;
    private static int numPools = 0;
    private static final PersistenceManager singleton = new PersistenceManager();
    protected static HashMap<String, EntityManagerFactory> emf;
    private Logger log = Logger.getLogger(PersistenceManager.class);

    public static synchronized PersistenceManager getInstance() {
        return singleton;
    }

    private PersistenceManager() {
        //if (emf==null) {
            //btnLogger.getLogger().debug("constructor de PersistenceManager");
            log.debug("constructor de PersistenceManager");
            emf = new HashMap<String, EntityManagerFactory>();

            // Crear los pools en el constructor
            // Alberto, 2011-12-13

            this.createEntityManagerFactory("jpa_basket");
        //}
    }

    public EntityManagerFactory getEntityManagerFactory(String db) {
        //btnLogger.getLogger().debug("[xxxx] getting mf ... " + db + " >>> get: " + emf.get(db));
        log.debug("[xxxx] getting mf ... " + db + " >>> get: " + emf.get(db));

        /*
        if (emf.get(db)==null) {
            createEntityManagerFactory(db);
        }
         *
         */

        return emf.get(db);
    }

    public void closeEntityManagerFactory(String db) {
        //btnLogger.getLogger().debug("closeEntityManagerFactory ... db = " + db);
        log.debug("closeEntityManagerFactory ... db = " + db);
        if (emf.get(db) != null) {
            emf.get(db).close();
            emf.remove(db);
            if (DEBUG)
                //btnLogger.getLogger().debug("n*** Persistence " + db + " finished at " + new java.util.Date());
                log.debug("n*** Persistence " + db + " finished at " + new java.util.Date());
        }
    }

    protected void createEntityManagerFactory(String db) {
        try {
            //btnLogger.getLogger().debug("[xxx] creando mf ... " + db + " ... get: " + emf.get(db) + " ...numPools: " + ++numPools);
            log.debug("[xxx] creando mf ... " + db + " ... get: " + emf.get(db) + " ...numPools: " + ++numPools);
            if (emf.get(db)==null) {
                this.emf.put(db, Persistence.createEntityManagerFactory(db));
                if (DEBUG) {
                    //btnLogger.getLogger().debug("n*** Persistence " + db + " started at " + new java.util.Date());
                    log.debug("n*** Persistence " + db + " started at " + new java.util.Date());
                }
            }
        } catch (Exception e) {
            //btnLogger.getLogger().error("[createEntityManagerFactory]: Error " + e);
            log.error("[createEntityManagerFactory]: Error ", e);
        }
    }
}

